package ru.housewife.service.user;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.validation.Errors;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.UserForm;
import ru.housewife.model.Region;
import ru.housewife.model.User;

import java.util.List;

/**
 * saves new user in DB
 *
 * @author Alexander Troshanin
 */
public class RegisterNewUser implements HibernateAction<Void> {

    private final UserForm userForm;

    private final Errors errors;

    public RegisterNewUser(UserForm userForm, Errors errors) {
        this.userForm = userForm;
        this.errors = errors;
    }

    @Override
    public Void execute(Session session) {
        Query q1 = session.createQuery("select u from User u where u.userName=:userName");
        q1.setString("userName", userForm.getUserName());
        List lst1 = q1.list();
        if (lst1 != null && lst1.size() > 0) {
            errors.rejectValue("userName", "registration.fail.username.already.used");
        }
        Query q2 = session.createQuery("select u from User u where u.email=:email");
        q2.setString("email", userForm.getEmail());
        List lst2 = q2.list();
        if (lst2 != null && lst2.size() > 0) {
            errors.rejectValue("email", "registration.fail.email.already.used");
        }
        if (errors.hasErrors()) {
            return null;
        }
        Region region = null;
        if (userForm.getRegion() != null) {
            region = (Region) session.get(Region.class, userForm.getRegion().getId());
        }
        User user = new User();
        user.setUserName(userForm.getUserName());
        user.setUserPass(userForm.getUserPass());
        user.setFullName(userForm.getFullName());
        user.setEmail(userForm.getEmail());
        user.setRegion(region);
        session.save(user);
        userForm.setId(user.getId());
        return null;
    }
}
